#!/bin/bash
#description tongdian service

source /etc/init.d/functions

ENV="test"

TONGDIAN_PS=''
TONGDIAN_PID=0
checktongdian(){
  TONGDIAN_PS=$(ps aux | grep 'hongen-tongdian.jar' | grep -v 'grep')
  TONGDIAN_PID=$(echo $TONGDIAN_PS | awk '{print $2}')
}

start(){
  checktongdian
  if [ ! -z "$TONGDIAN_PS" ];then
    action "tongdian service is started, pid: $TONGDIAN_PID"
    return 0
  else
    echo -n "tongdian is starting ..."
    now=$(date "+%Y%m%d%H%M%S")
    sh /usr/local/tongdian/shell/start_tongdian.sh $now
    for i in {1..100};do
      started_log=$(grep "Tomcat started" /var/log/tongdian/tongdian-$now.log)
      if [ ! -z "$started_log" ];then
        echo ""
        echo "$started_log"
        status
        return 0
      else
        sleep 2
        echo -n " ..."
      fi
    done
  fi
}

stop(){
  checktongdian
  if [ -z "$TONGDIAN_PS" ];then
    action "tongdian service is stopped"
  else
    echo "stopping tongdian service (pid: $TONGDIAN_PID) ..."
    kill -9 $TONGDIAN_PID
    for i in {1..100};do
      checktongdian
      test -z "$TONGDIAN_PS" && action "tongdian service is stopped" && return 0 || echo -n " ..."
      sleep 2
    done
  fi
}

status(){
  checktongdian
  if [ ! -z "$TONGDIAN_PS" ];then
    action "tongdian service is running, pid: $TONGDIAN_PID"
  else
    action "tongdian service is stopped"
  fi
}

update(){
  echo "tongdian service is updating ..."
  rm -rf /tmp/deploy
  svn export svn://svnserver/deploy /tmp/deploy --username=deploy --password=hongen0916
  if [ ! -f /tmp/deploy/hongen-tongdian-$ENV.jar ];then
    action "/tmp/deploy/hongen-tongdian-$ENV.jar not found" /bin/false
    exit -1
  fi
  stop
  rm -f /usr/local/tongdian/app/*.jar
  cp /tmp/deploy/hongen-tongdian-$ENV.jar /usr/local/tongdian/app/hongen-tongdian.jar
  start
  action "tongdian service is updated."
}

case $1 in 
start)
    start
    ;;
stop)
    stop
    ;;
status)
    status
    ;;
restart)
    stop
    start
    ;;
update)
    update
    
    ;;
*)
    echo "usage: java status | stop | start | restart | update"
    ;;
esac

